/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.service.pf.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.pf.BaseBusinessIndicatorsOld;
import com.plian.system.entity.pf.BusinessIndicatorsOld;
import com.plian.system.mapper.pf.BaseBusinessIndicatorsOldMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.pf.IBaseBusinessIndicatorsOldService;
import com.plian.system.service.pf.IBusinessIndicatorsOldService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pf.BaseBusinessIndicatorsOldVO;
import com.plian.system.wrapper.pf.BaseBusinessIndicatorsOldWrapper;
import com.plian.system.wrapper.pf.BusinessIndicatorsOldWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 经营业绩考核指标主表 服务实现类
 *
 * @author
 * @since 2019-09-27
 */
@Slf4j
@Service
@AllArgsConstructor
public class BaseBusinessIndicatorsOldServiceImpl extends BaseServiceImpl<BaseBusinessIndicatorsOldMapper, BaseBusinessIndicatorsOld> implements IBaseBusinessIndicatorsOldService, BaseFlowService {

	private FormWorkflowService formWorkflowService;

	private IFormCodeService formCodeService;

	private IBusinessIndicatorsOldService businessIndicatorsService;

	private BusinessIndicatorsOldWrapper businessIndicatorsWrapper;

	private BaseBusinessIndicatorsOldWrapper baseBusinessIndicatorsWrapper;

	@Override
	public boolean saveOrUpdate(BaseBusinessIndicatorsOld baseBusinessIndicators) {

		if (!Optional.ofNullable(baseBusinessIndicators.getStatus()).isPresent()) {
			baseBusinessIndicators.setStatus(FormStatusConstant.UNREVIEWED);
		}
		if (!Optional.ofNullable(baseBusinessIndicators.getId()).isPresent()) {
			baseBusinessIndicators.setCode(formCodeService.getCode(FormTypeConstant.PF_BASE_BUSINESS_INDICATORS_OLD));
			baseBusinessIndicators.setFormType(String.valueOf(FormTypeConstant.PF_BASE_BUSINESS_INDICATORS_OLD));
		}

		return super.saveOrUpdate(baseBusinessIndicators);
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean deleteLogic(List<Long> ids) {
		for (Long id : ids) {
			BaseBusinessIndicatorsOld baseBusinessIndicators = getById(id);
			if (baseBusinessIndicators == null) {
				return false;
			} else if (baseBusinessIndicators.getStatus() != null &&
					(baseBusinessIndicators.getStatus() != FormStatusConstant.STASH && baseBusinessIndicators.getStatus() != FormStatusConstant.UNREVIEWED)) {
				return false;
			}
			formWorkflowService.deleteProcessInstance(String.valueOf(id));
		}

		boolean result = super.deleteLogic(ids);
		if (result){
			businessIndicatorsService.deleteByParentId(ids);
		}

		return result;
	}

	@Override
	public HashMap<String,Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String,Object>();
	}

	@Override
	public Boolean finish(String id) {
		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
	}

	@Override
	public Boolean reject(String id, int formState, String comment) {
		return handleStatus(Long.valueOf(id), formState);
	}

	@Override
	public String checkYear(BaseBusinessIndicatorsOld baseBusinessIndicators) {
//		QueryWrapper<BaseBusinessIndicators> queryWrapper = new QueryWrapper<>();
		if (!Optional.ofNullable(baseBusinessIndicators.getFillingYear()).isPresent()) {
			return "填报时间为空";
		}
		if (!Optional.ofNullable(baseBusinessIndicators.getFillingUnitId()).isPresent()){
			return "填报单位为空";
		}
		return null;
//		queryWrapper.eq("filling_unit_id",baseBusinessIndicators.getFillingUnitId());
//		queryWrapper.eq("filling_year", baseBusinessIndicators.getFillingYear());
//		BaseBusinessIndicators one = getOne(queryWrapper);
//		if (!Optional.ofNullable(one).isPresent()){
//			return null;
//		}
//		if (one.getId().equals(baseBusinessIndicators.getId())){
//			return null;
//		}
//		return "该年度已填报";
	}


	/**
	 * 统一处理状态机事件方法
	 *
	 * @param id          主键
	 * @param updateStatus  更新状态
	 * @return boolean
	 */
	private Boolean handleStatus(Long id, int updateStatus) {
		try {
			BaseBusinessIndicatorsOld baseBusinessIndicators = getById(id);
			/**
			 * 设置审批人和审批时间
			 */
			if (updateStatus == FormStatusConstant.FINISH){
				baseBusinessIndicators.setApprovedUser(TokenUtil.getTokenUserId());
				Date now = DateUtil.now();
				baseBusinessIndicators.setApprovedTime(now);
			}
			baseBusinessIndicators.setStatus(updateStatus);
			updateById(baseBusinessIndicators);
			return true;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
	}


	@Override
	public List<PageData> findByIds(List<String> formIds) {
		LambdaQueryWrapper<BaseBusinessIndicatorsOld> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(BaseBusinessIndicatorsOld::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
		List<BaseBusinessIndicatorsOld> baseBusinessIndicators = list(queryWrapper);
		List<BaseBusinessIndicatorsOldVO> baseBusinessIndicatorsVOS = baseBusinessIndicatorsWrapper.entityToVO(baseBusinessIndicators);

		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(baseBusinessIndicatorsVOS)){
				for (BaseBusinessIndicatorsOldVO vo : baseBusinessIndicatorsVOS){
					PageData pd = new PageData();
					pd.put("id", vo.getId());
					pd.put("UNITNAME", vo.getFillingUnitName());
					pd.put("APPLICANTNAME", vo.getCreateUserName());
					pd.put("applicantId", vo.getCreateUser());
					pd.put("applyOrganizationId", vo.getFillingUnitId());
					pd.put("formType", FormTypeConstant.PF_BASE_BUSINESS_INDICATORS_OLD);
					pd.put("orgName", vo.getFillingUnitName());
					pageDataList.add(pd);
				}
			}

			return pageDataList;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Arrays.asList(FormTypeConstant.PF_BASE_BUSINESS_INDICATORS_OLD);
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean submit(BaseBusinessIndicatorsOld baseBusinessIndicators) {
		boolean result = saveOrUpdate(baseBusinessIndicators);
		if (result){
			List<BusinessIndicatorsOld> businessIndicatorsList = baseBusinessIndicators.getBusinessIndicators();
			if (CollectionUtil.isNotEmpty(businessIndicatorsList)){
				for (BusinessIndicatorsOld businessIndicators : businessIndicatorsList){
					if (businessIndicators.getId() != null &&
							Optional.ofNullable(businessIndicators.getIsDeleted()).isPresent() && businessIndicators.getIsDeleted().intValue() == 1) {
						businessIndicatorsService.removeById(businessIndicators.getId());
					}else {
						businessIndicators.setBaseBusinessIndicatorsId(baseBusinessIndicators.getId());
						businessIndicatorsService.saveOrUpdate(businessIndicators);
					}
				}
			}
		}
		return result;
	}

	@Override
	public R<BaseBusinessIndicatorsOldVO> getDetailObj(BaseBusinessIndicatorsOldVO baseBusinessIndicatorsVO) {
		if(!Optional.ofNullable(baseBusinessIndicatorsVO).isPresent()){
			return new R(CommonCode.FAIL);
		}
		List<BusinessIndicatorsOld> list = businessIndicatorsService.list(new LambdaQueryWrapper<BusinessIndicatorsOld>()
				.eq(BusinessIndicatorsOld::getBaseBusinessIndicatorsId, baseBusinessIndicatorsVO.getId()));
		baseBusinessIndicatorsVO.setBusinessIndicators(list);

		baseBusinessIndicatorsVO.setBusinessIndicatorsVOS(businessIndicatorsWrapper.entityToVO(list));
		R<BaseBusinessIndicatorsOldVO> objResult = new R<>(CommonCode.SUCCESS);
		objResult.setPageData(baseBusinessIndicatorsVO);
		return objResult;
	}

	@Override
	public void goBackToStash(String formId) {
		handleStatus(Long.valueOf(formId), UNREVIEWED);
	}
}
